import {
  cloneDeep,
  findIndex,
  each,
  isArray
} from 'lodash'
import { getZhexianByDay, submitData } from '@/api/tableAndBarlineMarker'

const markItemStyle = {
  itemStyle: {
    color: '#c23531'
  },
  label: {
    formatter: function (val) {
      return val.name
    }
  }
}

export default {
  data() {
    return {
      resultSubmitData: []
    }
  },
  methods: {
    showWraningNotice (title = undefined, desc) {
      this.$Notice.warning({
        title: title || '操作提示',
        desc
      })
    },
    /**
     * @msg: 显示加载
     * @param {type}
     * @return:
     */
    showLoading () {
      this.$Spin.show({
        render: h => {
          return h('div', [
            h('Icon', {
              class: 'spin-icon-load',
              props: {
                type: 'ios-loading',
                size: 20
              }
            }),
            h('div', '图表生成中...')
          ])
        }
      })
    },
    /**
     * @msg: 隐藏loading
     * @param {type}
     * @return:
     */
    hideLoading () {
      this.$Spin.hide()
    },
    /**
     * @msg: 整理一天折线图数据
     * @param {type}
     * @return:
     */
    modifyZhexianByDayData (data) {
      const filterMarkData = this.filterMarkData()
      const retArr = []
      const xAxisData = []
      let markData = []
      each(data, (item, index) => {
        const { hour, usage, mark } = item
        retArr.push({
          name: hour,
          value: usage,
          hour,
          mark,
          index
        })
        xAxisData.push(hour)
        if (mark && markData.length < 2) {
          let type = 'min'
          let name = '开始'
          if (markData.length !== 0) {
            type = 'max'
            name = '结束'
          }
          markData.push({
            ...markItemStyle,
            type,
            name,
            hour,
            index: hour - 1,
            coord: [hour - 1, usage],
            value: usage
          })
        }
      })
      this.zhexianDayData = {
        seriesData: retArr,
        xAxisData
      }

      this.showMeterDayModel = true

      this.currentMarkData = filterMarkData || markData
    },
    /**
     * @msg: 从已保存的数据中筛选已设置的数据
     * @param {type}
     * @return: null || 设置好的markData
     */
    filterMarkData () {
      const retData = this.resultSubmitData
      const len = retData.length
      const { meterId } = this.options
      let retMarkData = null
      for (let i = 0; i < len; i++) {
        if (meterId === retData[i].meterId) {
          const { startValue, endValue, start, end } = retData[i]
          retMarkData = [
            {
              ...markItemStyle,
              type: 'min',
              index: start - 1,
              name: '开始',
              coord: [start - 1, startValue],
              value: startValue,
              hour: start
            },
            {
              ...markItemStyle,
              type: 'max',
              index: end - 1,
              name: '结束',
              coord: [end - 1, endValue],
              value: endValue,
              hour: end
            }
          ]
          break
        }
      }
      return retMarkData
    },
    /**
     * @msg: 获取一天的折线图数据
     * @param {type}
     * @return:
     */
    fetchZhexianByDayData (params) {
      this.showLoading()
      this.hasMoveFlag = true
      this.zhexiantuFinishedStatus = false
      this.zhexiantuHasSelected = false
      this.zhexianSelectedPoints = null
      this.zhexianKeyUpSelecteIndex = 0
      getZhexianByDay(params).then(res => {
        this.hideLoading()
        if (res.date) {
          this.hasMoveFlag = false
          this.modifyZhexianByDayData(res.date)
        }
      })
    },
    /**
     * @msg: 设置起始和结束
     * @param {type}
     * @return:
     */
    zhexianContextMenuSelectHandle (data, type) {
      if (type === 'cancel') {
        return this.zhexianContextMenuCancelHandle(data)
      }
      let value = 0
      const { index } = data
      value = data.value
      if (isArray(data.value)) {
        value = data.value[1]
      }
      const markDataLen = this.currentMarkData.length
      const currentArr = cloneDeep(this.currentMarkData)
      if (markDataLen < 2) {
        if (markDataLen === 0 && type === 'min') {
          currentArr.push({
            ...data,
            ...markItemStyle,
            type,
            index,
            value,
            name: '开始',
            coord: [index, value]
          })
        } else if (markDataLen === 0 && type === 'max') {
          currentArr.push({
            ...data,
            ...markItemStyle,
            type,
            index,
            value,
            name: '结束',
            coord: [index, value]
          })
        } else {
          const firstData = currentArr[0]
          if (type === firstData.type) {
            return this.showWraningNotice('', '同类型点已存在')
          }
          if (index === firstData.xAxis) {
            return this.showWraningNotice('', '同一个点不能重复设置')
          }
          if ((type === 'max' && index < firstData.index) || (type === 'min' && index > firstData.index)) {
            return this.showWraningNotice('', '起始不能小于结束')
          }
          if (index >= firstData.index) {
            currentArr.push({
              ...data,
              ...markItemStyle,
              type,
              index,
              value,
              name: '结束',
              coord: [index, value]
            })
          } else {
            currentArr.unshift({
              ...data,
              ...markItemStyle,
              type,
              index,
              value,
              name: '开始',
              coord: [index, value]
            })
          }
        }

        this.currentMarkData = currentArr
      } else {
        this.showWraningNotice('', '起始数据和结束数据已存在不能再添加')
      }
    },
    /**
     * @msg: 取消设置
     * @param {type}
     * @return:
     */
    zhexianContextMenuCancelHandle (data) {
      const { value, index } = data
      const oldData = cloneDeep(this.currentMarkData)
      const num = findIndex(oldData, o => {
        return o.value === value && o.index === index
      })
      if (num >= 0) {
        oldData.splice(num, 1)
      }
      this.currentMarkData = oldData
    },
    /**
     * @msg: 天数折线图点击
     * @param {type}
     * @return:
     */
    zhexianDayClickHandle (params = {}) {
      const { data = {} } = params
      const { hour } = data

      this.getMeterDetailByTime(hour)
    },
    /**
     * @msg: 保存数据
     * @param {type}
     * @return:
     */
    saveData () {
      const len = this.currentMarkData.length
      if (!len) {
        this.showWraningNotice('', '没有可保存的数据')
      } else if (len === 1) {
        this.showWraningNotice('', '数据不完整，必须同时设置起始和结束')
      } else {
        const { day = undefined } = this.options
        const { meterId } = this.options
        const [startData, endData] = this.currentMarkData
        const data = {
          meterId,
          tId: day || this.defaultDate,
          start: startData.hour,
          end: endData.hour,
          startValue: startData.value,
          endValue: endData.value
        }
        this.resultSubmitData.push(data)
        this.$Message.success('保存成功')
      }
    },
    /**
     * @msg: 数据提交
     * @param {type}
     * @return:
     */
    submitData () {
      const len = this.resultSubmitData.length
      if (!len) {
        this.showWraningNotice('', '没有可提交的数据')
      } else {
        submitData(this.resultSubmitData)
          .then(res => {
            this.$Message.success(res.msg)
          })
          .catch(e => {
            this.$Message.error('提交失败')
          })
      }
    }
  }
}
